package cn.com.taiji.oospub.wechat.controller;


import cn.com.taiji.common.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.entity.Restaurant;
import cn.com.taiji.oospub.wechat.service.IRestaurantService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 餐厅 前端控制器
 * </p>
 *
 * @author yzd
 * @since 2020-12-14
 */
@RestController
@RequestMapping("/wx/restaurant")
public class RestaurantController {
    @Autowired
    private IRestaurantService restaurantService;

    @RequestMapping(value = "/getAllRestaurants", method = RequestMethod.GET)
    @ResponseBody
    public String getAllRestaurants(HttpServletRequest request, HttpServletResponse response, Model model) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        //获取已选中的餐厅
        Restaurant restaurant = member.getRestaurant();
        if (restaurant == null) {
            //设置第一个可用餐厅为默认餐厅
            QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_stop", false);
            queryWrapper.eq("school_id", member.getSchoolId());
            restaurant = restaurantService.list(queryWrapper).get(0);
        }
        model.addAttribute("checked", restaurant);
        String schoolId = member.getSchoolId();
        QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_stop", 0);
        queryWrapper.eq("school_id", schoolId);
        List<Restaurant> list = restaurantService.list(queryWrapper);
        model.addAttribute("restaurants", list);
        return JSONObject.toJSONString(model);
    }


    @RequestMapping(value = "/setRestaurant", method = RequestMethod.POST)
    @ResponseBody
    public String getAllRestaurants(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        member.setRestaurant(restaurantService.getById(id));
        WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, member);
        WebUtils.setSessionAttribute(request, "restaurantId", id);
        return JSONObject.toJSONString(member);
    }


}
